package lec05.pm.v3;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
//enum OPERATOR_TYPE{
//	ADD,SUB,MUL,DIV;
//}

public class Calculator extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	final static int UNKNOW = -1;
	final static int ADD = 0;
	final static int SUB = ADD + 1;
	final static int MUL = SUB + 1;
	final static int DIV = MUL + 1;

	protected double first_operand;
	protected double second_operand;
	int operator;

	final static String[] LABEL = "7 8 9 / Sqrt 4 5 6 * % 1 2 3 - 1/x 0 +/- . + ="
			.split(" ");
	JTextField screen;
	JPanel panel;
	JButton[] btns = new JButton[20];

	public Calculator() {
		this.setLayout(new BorderLayout());
		this.add(screen = new JTextField(), BorderLayout.NORTH);
		screen.setAlignmentX(RIGHT_ALIGNMENT);
		screen.setText("0");
		panel = new JPanel();
		panel.setLayout(new GridLayout(4, 5));
		for (int i = 0; i < 20; i++) {
			panel.add(btns[i] = new JButton(LABEL[i]));
			btns[i].addActionListener(this);
		}
		this.add(panel, BorderLayout.CENTER);
		setSize(400, 500);
		setVisible(true);

	}

	public static void main(String[] args) {
		new Calculator();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		boolean flag = false;
		for (int i = 0; i < btns.length; i++)
			if (e.getSource() == btns[i]) {
				flag = true;
				break;
			}

		if (flag) {
			JButton cur = (JButton) (e.getSource());
			if ("0123456789".contains(cur.getText())) {
				if (screen.getText().equals("0"))
					screen.setText(cur.getText());
				else
					screen.setText(screen.getText() + cur.getText());
			} else if ("+-*/".contains(cur.getText())) {
				first_operand = Double.parseDouble(screen.getText());
				operator = "+-*/".indexOf(cur.getText());
				screen.setText("0");

			} else if ("=".contains(cur.getText())) {
				second_operand = Double.parseDouble(screen.getText());
				switch (operator) {
				case ADD:
					screen.setText(Double.toString(first_operand+second_operand));
					break;
				case SUB:
					screen.setText(Double.toString(first_operand-second_operand));
					break;
				case MUL:
					screen.setText(Double.toString(first_operand*second_operand));
					break;
				case DIV:
					screen.setText(Double.toString(first_operand/second_operand));
					break;
				default:
					break;
				}
				//operator=UNKNOW;

			}
		}

	}
}
